package com.firefly.web.filter;

import com.firefly.dao.util.RedisUtils;
import com.firefly.util.handle.FireflyException;
import com.firefly.util.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: API接口权限检查
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/9/7
 **/
@WebFilter(filterName = "ApiFilter", urlPatterns = "/api/*")
@Slf4j
public class ApiJwtFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {}

    private final RedisUtils redisUtils;

    @Autowired
    public ApiJwtFilter(RedisUtils redisUtils){
        this.redisUtils = redisUtils;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            Map m = new HashMap<String, String[]>(httpRequest.getParameterMap());
            String actionName = httpRequest.getRequestURI();
            actionName = actionName.replace("/api/", "");
            String userId = null;
            Map urls = new HashMap<>();
            urls.put("wechat/code",1);
            urls.put("wechat/phone",1);
            urls.put("login/phone",1);
            urls.put("code/send",1);
            // urls.put("upload/file",1);
            if (urls.containsKey(actionName) == false) {
                // 开始解析用户token
                String token = httpRequest.getHeader("Authorization");
                // 验证token有效性
                log.debug("api token ----------------------------");
                log.debug(m.toString());
                // log.debug(token);
                userId = JWTUtil.verify(token);
                if (userId.equals("false")) {
                    throw new FireflyException(402,"登录失效，重新登录后再操作");
                }
                /*McLoginVo userMap = (McLoginVo) redisUtils.get("mc-token:" + userId);
                // log.debug(userMap.toString());
                if (userMap == null) {
                    returnJson(response,401,"登录已经失效，重新登录后再操作");
                }
                // 改造入参，给需要用户信息的追加用户信息
                List permissions = userMap.getUrls();
                // 不是创建者，没有角色 || 角色不是超级管理员同时没有url权限
                if(permissions.contains(actionName) == false && !userMap.getRoleId().equals(1)){
                    returnJson(response,402,"没有权限");
                }
                m.put("requestUserId", userMap.getId());
                m.put("requestAgentId", userMap.getAgentId());*/
                //继续向后传递修改后的request,同时修改返回值的header token,拦截器不能实现。
                String newToken = null;
                try {
                    newToken = JWTUtil.sign(userId, 30 * 24, "mc-token");
                } catch (Exception e) {
                    throw new RuntimeException("Token 生成失败，" + e.toString());
                }
                ((HttpServletResponse) response).setHeader("Authorization", newToken);
            }
            FireflyRequestWrapper parameterRequestWrapper = new FireflyRequestWrapper((HttpServletRequest) request, m);
            chain.doFilter(parameterRequestWrapper, response);
        }catch (Exception e){
            // 传递异常信息
            request.setAttribute("filter.error", e);
            // 指定处理该请求的处理器
            request.getRequestDispatcher("/error/throw").forward(request, response);
        }
    }

    @Override
    public void destroy() {}
}